import { NextResponse } from "next/server";
import { streamAIResponse } from "@/app/services/aiService";
import { Message, ApiProvider, DeepSeekModel } from "@/store/useAppStore";

export async function POST(req: Request) {
  try {
    const { messages, selectedApi, selectedDeepSeekModel, document } =
      (await req.json()) as {
        messages: Message[];
        selectedApi: ApiProvider;
        selectedDeepSeekModel?: DeepSeekModel;
        document?: {
          name: string;
          type: string;
          size?: number;
          content:
            | string
            | {
                html: string;
                text: string;
                mainContent: string;
                metadata?: any;
              }; // base64 content 或解析后的内容
        };
      };

    if (!messages || messages.length === 0) {
      return NextResponse.json(
        { error: "Messages are required" },
        { status: 400 }
      );
    }

    // 如果有文档，添加文档处理提示到消息中
    let processedMessages = [...messages];
    if (document) {
      console.log("收到文档:", {
        name: document.name,
        type: document.type,
        hasContent: !!document.content,
        contentType: typeof document.content,
      });
      // 在最后一条用户消息中添加文档处理指令
      const lastMessage = processedMessages[processedMessages.length - 1];
      if (lastMessage.role === "user") {
        let documentInfo = `\n\n[文档信息]\n文件名: ${document.name}\n文件类型: ${document.type}`;

        // 处理解析后的文档内容
        if (
          document.type === "parsed" &&
          typeof document.content === "object"
        ) {
          const parsedContent = document.content;
          console.log("处理解析后的文档内容:", {
            mainContentLength: parsedContent.mainContent.length,
            htmlLength: parsedContent.html.length,
            textLength: parsedContent.text.length,
          });
          documentInfo += `\n\n[文档内容]\n${parsedContent.mainContent}`;

          // 如果用户询问HTML相关的问题，也提供HTML内容
          if (
            lastMessage.content.toLowerCase().includes("html") ||
            lastMessage.content.toLowerCase().includes("代码") ||
            lastMessage.content.toLowerCase().includes("格式")
          ) {
            documentInfo += `\n\n[HTML格式内容]\n\`\`\`html\n${parsedContent.html}\n\`\`\``;
          }
        } else if (document.size) {
          // 处理Base64格式的文档
          documentInfo += `\n文件大小: ${(document.size / 1024 / 1024).toFixed(
            2
          )}MB`;
        }

        documentInfo += `\n\n请帮我分析这个Word文档并提供相关建议。请用正常的对话方式回复，只在需要展示HTML代码时使用\`\`\`html代码块格式。`;

        processedMessages[processedMessages.length - 1] = {
          ...lastMessage,
          content: `${lastMessage.content}${documentInfo}`,
        };
      }
    }

    // 调用 AI 服务进行处理，并获取流式响应
    const stream = await streamAIResponse(
      processedMessages,
      selectedApi,
      selectedDeepSeekModel
    );

    // 将流式响应直接返回给客户端
    return new Response(stream, {
      headers: {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        Connection: "keep-alive",
      },
    });
  } catch (error) {
    console.error("AI chat error:", error);
    return NextResponse.json(
      { error: "Failed to get AI response" },
      { status: 500 }
    );
  }
}
